//
//  LoginViewController.m
//  myfamily
//
//  Created by xiayiyong on 15/7/2.
//  Copyright © 2015年 我爱我家. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginViewModel.h"
#import "ViewController.h"
#import "AppDelegate.h"
#import "NSString+STRegex.h"
#import "UIColor+Extension.h"

@interface LoginViewController ()
@property (nonatomic, strong)LoginViewModel* viewModel;
@property (nonatomic, strong)UITextField* usernameTextField;
@property (nonatomic, strong)UITextField* passwordTextField;
@property (nonatomic, strong)UIButton* loginButton;
@property (nonatomic, strong)UIButton* loginButton2;

@end

@implementation LoginViewController

#pragma mark - View lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.viewModel=[LoginViewModel new];
    
    [self.view addSubview:self.usernameTextField];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.loginButton2];
    [self layoutUIView];
    [self bindUIVIewModel];
    
    [[[self.viewModel.checkInputSignal
       filter:^BOOL(NSNumber *value) {
           return value.boolValue;
       }]
      flattenMap:^RACStream *(id value) {
          return[self.viewModel signInSignal];
      }]
     subscribeNext:^(id x) {
         NSLog(@"");
     }];
};

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - Common methods
-(void)layoutUIView
{
    UIView *superview = self.view;
    int padding = 10;
    
    [self.usernameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@100);
        make.left.equalTo(superview.mas_left).offset(padding);
        make.right.equalTo(superview.mas_right).offset(-padding);
        make.height.equalTo(@44);
    }];
    
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@150);
        make.left.equalTo(superview.mas_left).offset(padding);
        make.right.equalTo(superview.mas_right).offset(-padding);
        make.height.equalTo(@44);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordTextField.mas_bottom).offset(padding);
        make.left.equalTo(superview.mas_left).offset(padding);
        make.right.equalTo(superview.mas_right).offset(-padding);
        make.height.equalTo(@44);
    }];
    
    [self.loginButton2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginButton.mas_bottom).offset(padding);
        make.left.equalTo(superview.mas_left).offset(padding);
        make.right.equalTo(superview.mas_right).offset(-padding);
        make.height.equalTo(@44);
    }];
}

#pragma mark - Common methods
-(void)bindUIVIewModel
{
    RACSignal *validUsernameSignal =
    [[self.usernameTextField.rac_textSignal
     distinctUntilChanged]
     map:^id(NSString *text) {
         return @([text isValidPhone]);
     }];
    
    RACSignal *validPasswordSignal =
    [[self.passwordTextField.rac_textSignal
     distinctUntilChanged]
     map:^id(NSString *text) {
         return @(text.length>3);
     }];
    
    RACSignal *validInput=[RACSignal
                           combineLatest:@[
                                           validUsernameSignal,
                                           validPasswordSignal,
                                           ]
                           reduce:^(NSNumber *usernameValid, NSNumber *passwordValid) {
                               return @(usernameValid.boolValue && passwordValid.boolValue);
                           }];
    
    RAC(self.usernameTextField, backgroundColor) =
    [validUsernameSignal
     map:^id(NSNumber *passwordValid){
         return[passwordValid boolValue] ? [UIColor clearColor]:[UIColor yellowColor];
     }];
    
    RAC(self.passwordTextField, backgroundColor) =
    [validPasswordSignal
     map:^id(NSNumber *passwordValid){
         return[passwordValid boolValue] ? [UIColor clearColor]:[UIColor yellowColor];
     }];
    
    [validInput subscribeNext:^(NSNumber*validInput){
        self.loginButton.enabled =[validInput boolValue];
        self.loginButton.backgroundColor= [validInput boolValue] ? [UIColor colorWithHex:0x41b0ff alpha:1]:[UIColor lightGrayColor];
    }];
    
    [[validInput filter:^BOOL(NSNumber* value) {
        return value.boolValue;
    }]subscribeNext:^(id x) {
        NSLog(@"zzzzz");
    }];
    
    /*
    [[[self.viewModel signInSignal]doNext:^(id x) {
        
    }]subscribeNext:^(id x) {
        NSLog(@"yyyyyy");
    }];
     */
    
    RAC(self.viewModel, username)=self.usernameTextField.rac_textSignal;
    RAC(self.viewModel, password)=self.passwordTextField.rac_textSignal;
    
    /*
     RAC(self.loginButton, enabled) = validInput;
     
     RAC(self.loginButton, backgroundColor) = [validInput map:^id(NSNumber *validInput) {
     return [validInput boolValue] ? [UIColor colorWithHex:0x41b0ff alpha:1]:[UIColor lightGrayColor];
     }];
     */
    
}

#pragma mark - UITextFieldDelegate Methods
- (void)textFieldDidChange:(UITextField*)textField
{
    
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return YES;
}

#pragma mark - UITextViewDelegate Methods

#pragma mark - getters and setters
-(UITextField *)usernameTextField
{
    //用户名
    if (_usernameTextField==nil)
    {
        _usernameTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _usernameTextField.backgroundColor = [UIColor clearColor];
        _usernameTextField.delegate=self;
        _usernameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"账号"
                                                                                attributes:@{ NSForegroundColorAttributeName : [UIColor blackColor] }];
        _usernameTextField.textColor = [UIColor blackColor];
        _usernameTextField.text = @"13866666666";
        _usernameTextField.font=[UIFont systemFontOfSize:16];
        _usernameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _usernameTextField.adjustsFontSizeToFitWidth = YES;
        [_usernameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    _usernameTextField.translatesAutoresizingMaskIntoConstraints = NO;
    
    return _usernameTextField;
}

-(UITextField *)passwordTextField
{
    //密码
    if (_passwordTextField==nil)
    {
        _passwordTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _passwordTextField.textColor = [UIColor blackColor];
        _passwordTextField.returnKeyType = UIReturnKeyDone;
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.delegate=self;
        _passwordTextField.text = @"111222";
        _passwordTextField.font=[UIFont systemFontOfSize:16];
        _passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"密码"
                                                                                   attributes:@{ NSForegroundColorAttributeName : [UIColor blackColor] }];
    }
    
    _passwordTextField.translatesAutoresizingMaskIntoConstraints = NO;
    
    return _passwordTextField;
}

-(UIButton *)loginButton
{
    if (_loginButton==nil)
    {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginButton setTitle:@"登陆" forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginButton setBackgroundColor:[UIColor colorWithHex:0x41b0ff alpha:1]];
        _loginButton.imageView.contentMode = UIViewContentModeCenter;
        _loginButton.translatesAutoresizingMaskIntoConstraints = NO;
        _loginButton.clipsToBounds=YES;
        _loginButton.layer.masksToBounds=YES;
        _loginButton.layer.borderWidth=1;
        _loginButton.layer.borderColor=[UIColor lightGrayColor].CGColor;
        _loginButton.layer.cornerRadius=5;
        
        /*
        [_loginButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [[_loginButton rac_signalForSelector:@selector(btnClick:)]
         subscribeNext:^(id x) {
             NSLog(@"btnClick挂钩");
         }];
         
         
         [[_loginButton rac_signalForControlEvents:UIControlEventTouchUpInside]
         subscribeNext:^(id x) {
         }];
         */

        [[[[_loginButton
            rac_signalForControlEvents:UIControlEventTouchUpInside]
           doNext:^(id x){ //在一个next事件发生时执行的逻辑，而该逻辑并不改变事件本身
               self.loginButton.enabled =NO;
               [self.usernameTextField resignFirstResponder];
               [self.passwordTextField resignFirstResponder];
           }]
          flattenMap:^id(id x){
              return[self.viewModel signInSignal];
          }]
         subscribeNext:^(id x) {
             self.loginButton.enabled =YES;
             if (self.viewModel.data.errorCode==0)
             {
                 ViewController *vc = [[ViewController alloc] init];
                 [[[UIApplication sharedApplication] delegate] window].rootViewController = vc;
                 self.loginButton.enabled =YES;
             }
             else
             {
                 UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                               message:self.viewModel.data.errorMsg
                                                              delegate:nil
                                                     cancelButtonTitle:@"确定"
                                                                    otherButtonTitles:nil];
                 
                 [alert show];
             }
         } error:^(NSError *error) {
             self.loginButton.enabled =YES;

             UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                           message:@"网络异常"
                                                          delegate:nil
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil];
             
             [alert show];
             
         } completed:^{
             
         }];
    }
    
    return _loginButton;
}

-(UIButton *)loginButton2
{
    if (_loginButton2==nil)
    {
        _loginButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginButton2 setTitle:@"登陆" forState:UIControlStateNormal];
        [_loginButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginButton2 setBackgroundColor:[UIColor colorWithHex:0x41b0ff alpha:1]];
        _loginButton2.imageView.contentMode = UIViewContentModeCenter;
        _loginButton2.translatesAutoresizingMaskIntoConstraints = NO;
        _loginButton2.clipsToBounds=YES;
        _loginButton2.layer.masksToBounds=YES;
        _loginButton2.layer.borderWidth=1;
        _loginButton2.layer.borderColor=[UIColor lightGrayColor].CGColor;
        _loginButton2.layer.cornerRadius=5;
        
        [[[[[_loginButton2
           rac_signalForControlEvents:UIControlEventTouchUpInside]
          flattenMap:^RACStream *(id value) {
              return self.viewModel.checkInputSignal;
          }]
         filter:^BOOL(NSNumber *value) {
             return value.boolValue;
         }]
        flattenMap:^RACStream *(id value) {
            return[self.viewModel signInSignal];
        }]
         subscribeNext:^(id x) {
             
             self.loginButton.enabled =YES;
             if (self.viewModel.data.errorCode==0)
             {
                 ViewController *vc = [[ViewController alloc] init];
                 [[[UIApplication sharedApplication] delegate] window].rootViewController = vc;
                 self.loginButton.enabled =YES;
             }
             else
             {
                 UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                               message:self.viewModel.data.errorMsg
                                                              delegate:nil
                                                     cancelButtonTitle:@"确定"
                                                     otherButtonTitles:nil];
                 
                 [alert show];
             }
         } error:^(NSError *error) {
             self.loginButton.enabled =YES;
             
             UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                           message:@"网络异常"
                                                          delegate:nil
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil];
             
             [alert show];
             
         } completed:^{
             
         }];
    }
    
    return _loginButton2;
}


@end
